package com.xiang.controller;

import com.alibaba.fastjson.JSONObject;
import com.xiang.annotation.AccessLimit;
import com.xiang.common.Result;
import com.xiang.utils.CommonConstant;
import com.xiang.utils.DeviceUpgradeUtils;
import com.xiang.utils.MobileNumberValidator;
import com.xiang.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@RestController
@RequestMapping("/sys/common")
public class CommonController {

    @Autowired
    RedisUtil redisUtil;

    @PostMapping("sendCaptcha")
  @AccessLimit(limit = 10)
    public Result sendCaptcha(@RequestBody JSONObject json) {
        String mobile = json.getString("mobile");
        if (StringUtils.isBlank(mobile)) {
            return Result.error("参数异常！");
        }
        boolean validate = MobileNumberValidator.validate(mobile);
        if (!validate) {
            return Result.error("手机号格式错误！");
        }
        //生成验证码
        String captcha = DeviceUpgradeUtils.getCaptcha();
        if (Objects.isNull(captcha)) {
            return Result.error("验证码生成失败，请重试！");
        }
        //只能生成纯数字 正则表达式匹配
        while (!captcha.matches("\\d+")){
            captcha = DeviceUpgradeUtils.getCaptcha();
        }
        // 发送短信验证码  动态配置是否真实发送

        //缓存验证码
        redisUtil.set(CommonConstant.CAPTCHA_PREFIX + mobile, captcha, 300);
        return Result.OK(captcha);

    }


}
